import {
  APP_ID,
  CLIENT,
  PlATFORM,
  TOKEN_KEY
} from "../config";
import {
  ResultMessageEnum
} from '../config/resultMessageEnum'
import LocalStorage from '../utils/localStorage'
import {loginController} from "../utils/login"
let loadingCount = 0;

const tryStartLoading = () => {
  if (loadingCount === 0) {
    tt.showLoading();
  }
  loadingCount++;
}

const tryHideLoading = () => {
  loadingCount--;
  if (loadingCount === 0) {
    tt.hideLoading();
  }
}


export const request = (options) => {
  options.method && (options.method = options.method.toUpperCase())
  options.loading ??= true;
  return new Promise((resolve, reject) => {
    options.loading && tryStartLoading()
    tt.request({
      url: options.url,
      method: options.method || "GET",
      data: options.data || {},
      header: Object.assign({}, options.header, {
        'content-type': "application/json",
        'authorization': LocalStorage.getItem(TOKEN_KEY),
        'client': CLIENT,
        'platform': PlATFORM,
        "app-id": APP_ID
      }),
      success: (res) => {
        if (res.statusCode == 200 && res.data.code == 200) {
          resolve(res.data)
        } else if (res.statusCode == 200 && res.data.code !== 200) {
          reject(res.data.msg)
        } else {
          reject(res.data.error)
        }
      },
      fail: (err) => {
        reject(err)
      },
      complete: () => {
        options.loading && tryHideLoading()
      }
    });
  })
}


export const http = async (options) => {
  if (!loginController.isDeveloperServerLogin()) {
      await loginController.login(true);
  }
  try {
    const result = await request(options);
    return result;
  } catch (error) {
    if (error === ResultMessageEnum.TOKEN_EXPIRE_MESSAGE) {
      loginController.logout();
    }
    throw error
  }
}

